<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############


class JFX_Block_Config{
	protected $blockId;
	protected $data = array();

	public function __construct(){
		$args = func_get_args();
		if(count($args)>0){
			$this->load($args[0]);
		}
	}

	public function load($blockId){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$id = $DB->escape($blockId);
		$q = "SELECT * FROM {$CONFIG->dbprefix}block_config WHERE block_id = '{$id}'";
		$rows = $DB->fetchAll($q);
		if(!is_array($rows)){
			$rows = array();
		}
		foreach($rows as $row){
			$this->data[$row['k']] = unserialize($row['v']);
		}
		$this->blockId = $blockId;
	}

	public function save(){
		if(empty($this->blockId)){
			throw new exception('The block configuration is not initialized!');
		}

		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		
		foreach($this->data as $k=>$v){

			$dbParams = array(
				'block_id' => $this->blockId,
				'k' => $k,
				'v' => serialize($v)
			);

			if($DB->countRows($CONFIG->dbprefix.'block_config', "block_id = '{$this->blockId}' AND k = '{$k}'")==0){
				
				$DB->insert($CONFIG->dbprefix.'block_config', $dbParams);
				
			}else{

				$DB->update($CONFIG->dbprefix.'block_config', $dbParams, "block_id = '{$this->blockId}' AND k = '{$k}'");

			}

		}

	}

	public function has($keyname){
		return array_key_exists($keyname, $this->data);
	}

	public function set($keyname, $data){
		$this->data[$keyname] = $data;
		$this->save();
	}

	public function get($keyname){
		return @$this->data[$keyname];
	}

}



